<template>
  <div id="orderSubmit">
    <NavBarTitle :NavBarTitle="NavBarTitle" />
    <div class="title">
      <div class="time">{{ day }} {{ hour }}出发</div>
      <div class="toTravel flex aCenter between">
        <div style="margin-left: 30px">
          <div class="city">{{ citysname }}</div>
          <!-- <div class="city">{{ s_address }}</div> -->
          <div class="Station">{{ s_site }}</div>
          <!-- <div class="Station">{{ sitesname }}</div> -->
        </div>
        <div class="ban flex column aCenter">
          <div class="type">{{ type }}</div>
          <div>
            <div class="arrow"></div>
            <div class="rotate"></div>
          </div>
          <div class="type">{{ mileage }}公里</div>
        </div>
        <div style="margin-right: 30px">
          <div class="city">{{ cityename }}</div>
          <div class="Station">{{ e_site }}</div>
        </div>
      </div>
      <div class="Departure">
        上车点：<span v-if="s_address == ''">{{ s_site }}</span
        ><span v-if="s_address != ''">{{ s_address }}</span>
      </div>
      <div class="Departure">
        下车点：<span v-if="e_address == ''">{{ e_site }}</span
        ><span v-if="e_address != ''">{{ e_address }}</span>
      </div>
    </div>
    <div v-if="false" class="cellF flex jCenter">
      <div class="cell">
        <van-cell
          title="购票须知"
          is-link
          :to="{
            path: '/TicketingInstructions',
            query: { title: '购票须知', type: 'gou' },
          }"
        />
        <van-cell
          title="退票说明"
          is-link
          :to="{
            path: '/TicketingInstructions',
            query: { title: '退票说明', type: 'tui' },
          }"
        />
      </div>
    </div>
    <div style="margin-top: 20px;">
      <div
        class="userInfoF flex jCenter"
        v-for="(item, index) in list"
        :key="index"
      >
        <div class="userInfo">
          <div class="name">{{ item.name }}</div>
          <div class="mobile">联系方式:{{ item.telephone | noneNum }}</div>
          <div class="IDCard">身份证:{{ item.idcard | noneId }}</div>
          <div class="btn" @click="delBtn(index)">
            <img src="../../assets/img/delIcon.png" />
          </div>
          <div style="width: 100%; margin-top: 13px" class="flex jCenter">
            <div
              style="width: 325.5px; height: 1px; background-color: #dedede"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <div class="addUserF flex jCenter">
      <div class="addUser">
        <van-cell title="添加/编辑乘客" to="/CommonInfo" is-link />
      </div>
    </div>
    <div class="loading flex aCenter jCenter column" v-if="isIssueTickets">
      <div
        class="flex aCenter jCenter"
        style="
          -webkit-border-radius: 10px;
          -moz-border-radius: 10px;
          border-radius: 10px;
          background-color: rgba(51, 51, 51, 0.8);
          width: 100px;
          height: 100px;
        "
      >
        <van-loading
          size="24px"
          class="flex column aCenter jCenter"
          color="#ffffff"
          type="spinner"
          >出票中...
        </van-loading>
      </div>
    </div>

    <div class="explainF">
      <div class="explain">保险说明：</div>
    </div>
    <van-tabbar>
      <div style="width: 93.9%; margin-left: 3.2%">
        <div>
          <van-checkbox v-model="checked">
            <div>
              我已仔细阅读<span
                @click.stop="
                  navTo('/TicketingInstructions', {
                    title: '购票须知',
                    type: 'gou',
                  })
                "
                >《购票须知》</span
              >
              <span>和</span>
              <span
                @click.stop="
                  navTo('TicketingInstructions', {
                    title: '退票说明',
                    type: 'tui',
                  })
                "
                >《退票说明》</span
              >
            </div>
          </van-checkbox>
        </div>
        <div class="flex between aCenter" style="margin: 8px 0 16px 0">
          <div>
            订单总额 <span class="moneyM">￥{{ totalPrice }}</span>
          </div>
          <div class="detailed" @click="showPopup">明细</div>
          <div>
            <van-button @click="addoOrder" color="#ff912f">提交订单</van-button>
          </div>
        </div>
        <!--<div>订单总额 <span class="moneyM">￥{{ticket_price*list.length}}</span></div>-->
        <!--<div>订单总额 <span class="moneyM">￥{{price}}</span></div>-->
      </div>
    </van-tabbar>
    <van-popup
      v-model="show"
      position="bottom"
      closeable
      close-icon="close"
      :overlay="false"
      :style="{ height: '20%' }"
    >
      <div class="services flex column" style="margin-top: 8%">
        <div>
          票<span style="opacity: 0">价</span>价：<span class="marL"
            >{{ webTicketPrice }}元 * {{ list.length }} 人</span
          >
        </div>
        <div>
          总人数：<span class="marL">{{ list.length }}人</span>
        </div>
        <div>
          总票价：<span class="marL">{{ webTicketPrice * list.length }}元</span>
        </div>
        <div>
          服务费：<span class="marL"
            >{{ service }}元 * {{ list.length }} 人</span
          >
        </div>
        <div>
          保险费：<span class="marL"
            >{{ premium }}元 * {{ list.length }} 人</span
          >
        </div>
      </div>
    </van-popup>
    <van-dialog
      :beforeClose="chargeBtn"
      title="该班次已停售"
      v-model="show_"
      show-cancel-button
      confirmButtonText="拨打电话"
    >
      <div class="dialog flex column aCenter jCenter">
        <div class="callAd">如需购买该班次，请联系管理员</div>
      </div>
    </van-dialog>
    <van-popup
      v-model="popupShow"
      round
      close-on-popstate
      :close-on-click-overlay="false"
      overlay-class="buyor-popup-style"
      position="center"
    >
      <div class="buor-style">
        <van-tabs v-model="buyor" color="#0fa1a0" swipeable animated>
          <van-tab title="购票须知" name="gou">
            <div class="txt-style" v-html="txt"></div>
          </van-tab>
          <van-tab title="退款说明" name="tui">
            <div class="txt-style" v-html="txt"></div>
          </van-tab>
        </van-tabs>
        <div class="btn-style">
          <van-button
            style="width: 100%"
            color="#0fa1a0"
            :disabled="countDown > 0"
            size="small"
            @click="agreen()"
            >阅读并同意{{
              countDown == 0 ? "" : "(" + countDown + ")s"
            }}</van-button
          >
        </div>
      </div>
    </van-popup>
    <Loading :isLoading="isLoading" />
    <div class="Mask flex column aCenter" v-if="payShow">
      <img class="MaskImg" src="../../assets/img/payBg.png" />
      <div class="finishBtn">
        <van-button square type="default" @click="finishPay"
          >已完成支付宝付款</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import NavBarTitle from "components/NavBarTitle.vue";
import Loading from "components/Loading.vue";
import { Dialog } from "vant";
import { info, alipayAddorder } from "@/api/home";

export default {
  data() {
    return {
      NavBarTitle: "订单提交",
      isActive: "-1",
      list: [],
      departuretime: "",
      day: "",
      hour: "",
      citysname: "",
      cityename: "",
      sitesname: "",
      siteename: "",
      s_address: "",
      s_site: "",
      e_address: "",
      e_site: "",
      type: "",
      mileage: "",
      ticket_price: "",
      sys_telephone: "",
      price: "",
      s_ticket: "",
      service: 4,
      premium: 1,
      show: false,
      show_: false,
      isLoading: true,
      isIssueTickets: false,
      payShow: false,
      checked: false,
      // 协议弹窗
      popupShow: false,
      // 协议定义
      buyor: "gou",
      // 协议内容
      txt: "",
      // 定时器
      countDown: 10,
      timer: null,
    };
  },
  filters: {
    noneNum(val) {
      var reg = /^(\d{3})\d{4}(\d{4})$/;
      return val.replace(reg, "$1****$2");
    },
    noneId(val) {
      return `${val.substring(0, 4)}**********${val.substring(val.length - 3)}`;
    },
  },
  components: {
    NavBarTitle,
    Loading,
    [Dialog.name]: Dialog,
  },
  computed: {
    totalPrice() {
      return (this.list.length * this.ticket_price).toFixed(1);
    },
    // 前端展示的票价
    webTicketPrice() {
      return (this.ticket_price - this.service - this.premium).toFixed(1);
    },
  },
  watch: {
    list() {
      this.price = this.list.length * this.ticket_price;
    },
    buyor() {
      this.getBuyor();
    },
  },
  methods: {
    // 同意协议
    agreen() {
      localStorage.setItem("is_checked", true);
      this.popupShow = false;
    },
    // 获取两种协议
    getBuyor() {
      const data = {
        token: this.$store.state.token,
      };
      let apiUrl = "";
      if (this.buyor == "gou") {
        apiUrl = this.$api.home.buynotice;
      } else if (this.buyor == "tui") {
        apiUrl = this.$api.home.retreatnotice;
      }
      this.$axios
        .post(this.$index + apiUrl, this.$Qs.stringify(data))
        .then((res) => {
          if (res.data.flag) {
            this.txt = res.data.data;
          } else {
            this.$toast(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 跳转页面
    navTo(path, query) {
      this.$router.push({ path, query: { ...query } });
    },
    //完成支付宝之后
    finishPay() {
      this.$router.replace("/myorder");
    },
    chargeBtn(action, done) {
      if (action === "confirm") {
        location.href = "tel:" + this.sys_telephone;
        this.show = false;
        this.$router.replace("/searchResult"); //需要测试
      } else if (action === "cancel") {
        done();
        this.$router.replace("/searchResult");
      }
      done();
    },
    getTel() {
      let data = {
        token: this.$store.state.token,
      };
      this.$axios
        .post(this.$index + this.$api.user.personal, this.$Qs.stringify(data))
        .then((res) => {
          console.log(res);
          if (res.data.flag) {
            this.sys_telephone = res.data.data.sys_telephone;
          } else {
            this.$toast.fail(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onBridgeReady(appId, timeStamp, nonceStr, package_, signType, paySign) {
      let self = this;
      console.log("进了支付方法");
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: appId, //公众号名称，由商户传入
          timeStamp: timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: nonceStr, //随机串nonceStr
          package: package_,
          signType: signType, //微信签名方式：
          paySign: paySign, //微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            self.$router.replace("/myorder");
          }
        }
      );
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            this.onBridgeReady(
              appId,
              timeStamp,
              nonceStr,
              package_,
              signType,
              paySign
            ),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent(
            "WeixinJSBridgeReady",
            this.onBridgeReady(
              appId,
              timeStamp,
              nonceStr,
              package_,
              signType,
              paySign
            )
          );
          document.attachEvent(
            "onWeixinJSBridgeReady",
            this.onBridgeReady(
              appId,
              timeStamp,
              nonceStr,
              package_,
              signType,
              paySign
            )
          );
        }
      } else {
        // this.onBridgeReady(appId, timeStamp, nonceStr, package_, signType, paySign);
      }
    },
    showPopup() {
      this.show = true;
    },
    addoOrder() {
      if (!this.checked) {
        Dialog.confirm({
          title: "温馨提示",
          message: `请先仔细阅读并同意《购票须知》和《退票说明》`,
          confirmButtonColor: "#0fa0a0",
        });
        return false;
      }
      let contacts_num = this.list.length;
      for (let i = 0; i < this.list.length; i++) {
        this.list[i]["contacts_id"] = this.list[i].id;
      }
      console.log(this.list);
      // let list = this.$Qs.stringify(this.list);
      let list = JSON.stringify(this.list);
      let data = {
        token: this.$store.state.token,
        id: this.$route.query.id,
        pt_id: this.$route.query.pt_id,
        contacts: list,
        contacts_num: contacts_num,
      };
      console.log(data);
      if (this.s_ticket >= contacts_num) {
        this.isIssueTickets = true;
        Dialog.confirm({
          title: "订单生成成功",
          message: "",
          confirmButtonText: "微信支付",
          cancelButtonText: "支付宝支付",
          confirmButtonColor: "#0fa0a0",
        })
          .then(() => {
            console.log("微信支付");
            this.$axios
              .post(this.$index + this.$api.home.pay, this.$Qs.stringify(data))
              .then((res) => {
                console.log(res);
                if (res.data.flag) {
                  this.isIssueTickets = false;
                  Dialog.confirm({
                    title: "订单生成成功",
                    message: `<div class="marB">${this.s_site}----${this.e_site}</div><div class="marB">乘客:${this.list.length}人</div><div class="marB">总费用:${res.data.data.order_price}</div><div class="marB">总票价:${res.data.data.price}</div><div class="marB">总保险费:${res.data.data.premium}元</div><div class="marB">总服务费:${res.data.data.service_charge}元</div><div class="marB">发车时间:${this.departuretime}</div>`,
                    confirmButtonText:
                      "支付" + "￥" + res.data.data.order_price,
                    cancelButtonText: "稍后支付",
                    confirmButtonColor: "#0fa0a0",
                  })
                    .then(() => {
                      this.onBridgeReady(
                        res.data.data.pay.appId,
                        res.data.data.pay.timeStamp,
                        res.data.data.pay.nonceStr,
                        res.data.data.pay.package,
                        res.data.data.pay.signType,
                        res.data.data.pay.paySign
                      );
                    })
                    .catch(() => {
                      this.$router.replace({
                        path: "/myorder",
                        query: { active: 1 },
                      });
                    });
                } else {
                  this.$toast(res.data.msg);
                  this.isIssueTickets = false;
                }
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {
            alipayAddorder(data)
              .then((res) => {
                console.log(res);
                if (res.data.flag) {
                  this.isIssueTickets = false;
                  Dialog.confirm({
                    title: "订单生成成功",
                    message: `<div class="marB">${this.s_site}----${this.e_site}</div><div class="marB">乘客:${this.list.length}人</div><div class="marB">总费用:${res.data.data.order_price}</div><div class="marB">总票价:${res.data.data.price}</div><div class="marB">总保险费:${res.data.data.premium}</div><div class="marB">总服务费:${res.data.data.service_charge}</div><div class="marB">发车时间:${this.departuretime}</div>`,
                    confirmButtonText:
                      "支付" + "￥" + res.data.data.order_price,
                    cancelButtonText: "稍后支付",
                    confirmButtonColor: "#0fa0a0",
                  })
                    .then(() => {
                      this.payShow = true;
                      if (this.payShow) {
                        location.href =
                          window.location.href +
                          "&token_user=" +
                          this.$store.state.token +
                          "&form=" +
                          res.data.data.html;
                      }
                      // location.href = window.location.href + '&form=' + res.data.data.html + '&token_user='+ this.$store.state.token
                    })
                    .catch(() => {
                      this.$router.replace({
                        path: "/myorder",
                        query: { active: 1 },
                      });
                    });
                } else {
                  this.$toast(res.data.msg);
                  this.isIssueTickets = false;
                }
              })
              .catch((err) => {
                console.log(err);
              });
          });
      } else {
        this.$toast("订票数量大于余票，余票为" + this.s_ticket + "张");
      }
    },
    delBtn(index) {
      if (this.list.length < 2) {
        this.$toast("至少保留一位乘客");
      } else {
        this.list.some((item, i) => {
          if (i == index) {
            this.list.splice(i, 1);
            return true;
          }
        });
      }
    },
    contacts() {
      let data = {
        token: this.$store.state.token,
        id: 0,
      };
      this.$axios
        .post(this.$index + this.$api.user.contacts, this.$Qs.stringify(data))
        .then((res) => {
          // console.log(res);
          if (res.data.flag) {
            this.list = res.data.data;
          } else {
            this.$toast(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    info() {
      let data = {
        token: this.$store.state.token,
        id: this.$route.query.id,
        pt_id: this.$route.query.pt_id,
      };
      this.$axios
        .post(this.$index + this.$api.home.info, this.$Qs.stringify(data))
        .then((res) => {
          console.log(res);
          if (res.data.flag) {
            this.day = res.data.data.day;
            this.hour = res.data.data.hour;
            this.citysname = res.data.data.citysname;
            this.cityename = res.data.data.cityename;
            this.sitesname = res.data.data.sitesname;
            this.siteename = res.data.data.siteename;
            this.s_ticket = res.data.data.s_ticket;
            this.type = res.data.data.type;
            this.mileage = res.data.data.mileage;
            this.s_address = res.data.data.s_address;
            this.s_site = res.data.data.s_site;
            this.e_address = res.data.data.e_address;
            this.e_site = res.data.data.e_site;
            this.ticket_price = res.data.data.ticket_price;
            this.departuretime = res.data.data.departuretime;
            this.service = res.data.data.service_charge;
            this.premium = res.data.data.premium;
            this.isLoading = false;
          } else {
            this.isLoading = true;
            if (res.data.msg == "该班次已停售") {
              this.show_ = true;
            }else{
              this.$toast(res.data.msg);
              setTimeout(() => {
                this.$router.go(-1);
              }, 1200);
            }
            // this.$toast({
            //     message: res.data.msg,
            //     duration: 1000,
            //     onClose: () => {
            //         this.$router.replace('/searchResult');
            //     }
            // });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    aliPay() {
      if (this.$route.query.form) {
        // localStorage.setItem('token_user',this.$route.query.token_user)
        var ua = navigator.userAgent.toLowerCase(); //获取判断用的对象
        var local = window.location.href; // 获取页面url
        if (
          local.indexOf("form=") != -1 &&
          ua.match(/MicroMessenger/i) != "micromessenger"
        ) {
          const form = decodeURIComponent(local.match(/form=(\S*)/)[1]);
          console.log(form);
          const div = document.createElement("div");
          div.id = "alipay";
          div.innerHTML = form;
          document.body.appendChild(div);
          console.log(document.getElementsByName("sign"));
          var sign = document
            .getElementsByName("sign")[0]
            .value.replace(/\s/g, "+");
          document.getElementsByName("sign")[0].value = sign;
          document.querySelector("#alipay").children[0].submit();
          // this.isLoading = false
        }
      }
    },
  },
  beforeMount() {
    if (!localStorage.getItem("is_checked")) {
      this.popupShow = true;
      this.timer = setInterval(() => {
        // 倒计时减少1秒
        this.countDown--;

        // 倒计时结束时清除定时器
        if (this.countDown <= 0) {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    } else {
      this.countDown = 0;
      this.checked = true;
    }
    if (localStorage.getItem("token_user")) {
      this.getTel();
      this.contacts();
      this.info();
      this.getBuyor();
    } else {
      this.aliPay();
    }
  },
  created() {},
};
</script>

<style scoped>
.btn-style {
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0), #ffffff);
  height: 60px;
  line-height: 60px;
}
.buyor-popup-style {
  height: 50%;
}
.buor-style {
  width: 240px;
  margin: 0 15px;
}
.txt-style {
  padding: 15px 0;
  height: 300px;
  overflow-y: scroll;
}
.txt-style::-webkit-scrollbar {
  width: 0.5em;
  background-color: transparent;
}

.txt-style::-webkit-scrollbar-thumb {
  background-color: transparent;
}

.txt-style::-webkit-scrollbar-track {
  background-color: transparent;
}

.Mask {
  position: fixed;
  top: 0;
  width: 100%;
  height: 100%;
  color: #ffffff;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 999;
}
.MaskImg {
  width: 90%;
}
.finishBtn {
  margin-top: 200px;
}
.marB {
  margin-bottom: 3px;
}
.services > div {
  font-size: 14px;
  color: #333333;
  margin-left: 12px;
  margin-top: 4px;
}

.marL {
  margin-left: 50px;
}

/deep/ .van-popup--bottom {
  bottom: 60px;
}

.detailed {
  font-size: 13px;
  color: #333333;
  margin-left: 20px;
}

.loading {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 2;
}

.loading /deep/ .van-loading__text {
  margin-top: 10px;
  color: #ffffff;
}

.moneyM {
  font-size: 19px;
  color: #ff0909;
  margin-left: 12px;
}

/deep/ .van-button--normal {
  height: 43.5px;
  line-height: 43.5px;
  border-radius: 10px;
  padding: 0 45px;
}

/deep/ .van-tabbar {
  height: auto;
  font-size: 15px;
  color: #333333;
  padding-top: 16px;
}

.active {
  opacity: 0;
}

.explainF {
  width: 100%;
  margin-bottom: 100px;
}

.explain {
  padding: 25px 30px;
  font-size: 14px;
  color: #888888;
}

.addUserF {
  width: 100%;
}

.addUser {
  width: 93.9%;
  height: 50px;
  background-color: #ffffff;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  overflow: hidden;
}

.addUser /deep/ .van-cell {
  font-size: 16px;
  color: #0fa0a0;
  padding: 14px 17px 12px 17px;
}

.addUser /deep/ .van-cell__right-icon {
  display: none;
}

.userInfoF {
  width: 100%;
}

.userInfo {
  position: relative;
  height: 118px;
  width: 93.9%;
  background-color: #ffffff;
}

.title {
  width: 100%;
  height: 220px;
  background-color: #0fa1a0;
  z-index: -1;
}

.Departure {
  font-size: 13px;
  color: #ffffff;
  margin-bottom: 10px;
  margin-left: 32px;
}

.time {
  font-size: 15px;
  color: #ffffff;
  margin-left: 30px;
  padding-top: 22px;
}

.arrow {
  width: 67px;
  height: 1px;
  background-color: #ffffff;
}

.rotate {
  margin-left: 62.25px;
  width: 4.75px;
  height: 1px;
  background-color: #ffffff;
  -webkit-transform: rotate(-25deg);
  -moz-transform: rotate(-25deg);
}

.city {
  font-size: 17px;
  color: #ffffff;
}

.Station {
  font-size: 13px;
  color: #ffffff;
  margin-top: 6px;
}

.type {
  font-size: 12px;
  color: #ffffff;
  margin-top: 6px;
  margin-bottom: 5px;
}

.toTravel {
  position: relative;
  width: 100%;
  height: 80px;
}

.ban {
  position: absolute;
  margin-left: 40%;
}

.cellF {
  width: 100%;
  height: 60px;
}

.cell {
  width: 93.9%;
  background-color: #ffffff;
  margin-top: -42px;
  border-bottom: 9px solid #f2f2f2;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  overflow: hidden;
}

.cell /deep/ .van-cell {
  padding: 12px 17px;
}

.btn {
  position: absolute;
  right: 30px;
  bottom: 30px;
}

.btn img {
  width: 20px;
  height: 20px;
}

.name {
  margin-left: 17px;
  font-size: 17px;
  color: #333333;
  margin-top: 16px;
}

.mobile {
  margin-left: 17px;
  font-size: 14px;
  color: #888888;
  margin-top: 16px;
}

.IDCard {
  margin-left: 17px;
  font-size: 14px;
  color: #888888;
  margin-top: 11px;
}
.dialog {
  height: 90px;
  font-size: 18px;
  color: #333333;
}
.callAd {
  font-size: 13px;
  color: #999999;
}
</style>
